package com.shanjupay.merchant.intercept;

import com.shanjupay.common.exception.BusinessException;
import com.shanjupay.common.exception.CommonErrorCode;
import com.shanjupay.common.exception.ErrorCode;
import com.shanjupay.common.exception.RestErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @projectName: shanjupay
 * @package: com.shanjupay.merchant.intercept
 * @className: GlobalExceptionHandler
 * @author: Eric
 * @description: TODO
 * @date: 2023/12/3 17:14
 * @version: 1.0
 */
@ControllerAdvice    // 与ControllerAdvice和ExceptionHandler注解实现全局异常处理
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processExcetion(HttpServletRequest request, HttpServletResponse response, Exception e){
        // 异常处理,返回给前端RestErrorResponse
        // 最终转换成Json数据=>添加注解@ResponseBody
        // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)标记抛出500的错误

        // 解析异常:1.BusinessException自定义异常    取出ErrorCode
        //         2.Exception不可预知异常          统一为99999异常
        if (e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            // 错误代码
            int code = errorCode.getCode();
            // 错误信息
            String desc = errorCode.getDesc();
            return new RestErrorResponse(String.valueOf(code),desc);
        }
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKNOWN.getCode()),CommonErrorCode.UNKNOWN.getDesc());
    }
}
